package pub.guoxin.oops.common.auth.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pub.guoxin.oops.common.auth.JwtUserVo;
import pub.guoxin.oops.common.auth.service.AuthUserService;
import pub.guoxin.oops.model.User;
import pub.guoxin.oops.repository.UserRepository;

import java.util.Objects;

/**
 * Created by stephan on 20.03.16.
 */
@Service("jwtUserDetailsService")
public class JwtUserDetailsServiceImpl implements UserDetailsService, AuthUserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = getUserByUsername(username);
        return JwtUserVo.convert(user);
    }

    @Override
    public User getUserByUsername(String username) {
        Objects.requireNonNull(username);
        User user = userRepository.findByUsername(username);
        if (!Objects.isNull(user)) {
            return user;
        }
        user = userRepository.findByMobile(username);
        if (!Objects.isNull(user)) {
            return user;
        }
        throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
    }

}
